<template>
  <van-overlay :show="visible">
    <div class="container">
      <div ref="divBackground" class="bg">签名区域</div>
      <canvas ref="canvas" id="canvas" />
      <div style="display:flex;justify-content:space-between;margin-top:5px;">
        <van-button style="width:24%" type="warning" icon="close" @click="handleCancel">取消</van-button>
        <van-button style="width:24%" icon="replay" @click="handleClear">重签</van-button>
        <van-button style="width:49%" type="primary" icon="passed" @click="handleConfirm">确认</van-button>
      </div>
    </div>
  </van-overlay>
</template>

<script>
import SignatureDraw from '@/util/draw.js'

export default {
  data() {
    return {
      image: '',
      draw: null,
      visible: false
    }
  },
  props: {
    value: {
      type: String
    },
    propHeight: {
      type: Number,
      default: 360
    },
    propVisible: {
      type: Boolean,
      default: false
    }
  },

  mounted() {
    this.init()
  },

  methods: {
    init() {
      const options = {
        el: this.$refs.canvas,
        width: document.body.clientWidth - 10,
        height: this.propHeight,
        callback: this.signCallback
      }
      this.draw = new SignatureDraw(options)
      this.draw.init()
      this.$refs.divBackground.style.height = `${this.propHeight}px`
    },
    signCallback(imageURL) {
      this.$emit('input', imageURL)
      this.image = imageURL
    },
    handleConfirm() {
      if (this.draw.isBlank()) {
        this.$notify.warning('签名内容不能为空，请先签名!')
        return
      }
      this.$emit('confirm', this.image)
      this.draw.clear()
    },
    handleClear() {
      this.draw.clear()
      this.$emit('input', '')
    },
    handleCancel() {
      this.draw.clear()
      this.$emit('cancel')
    },
    isBlank() {
      return this.draw.isBlank()
    }
  },
  watch: {
    propVisible(newValue) {
      this.visible = newValue
    }
  }
}
</script>

<style lang="scss" scoped>
.bg {
  position: absolute;
  display: flex;
  justify-content: center;
  align-items: center;
  width: 100%;
  font-size:24px;
  color:gray;
}
.container {
  width:100%;
  padding: 5px;
  background-color: #fff;
  display: flex;
  flex-direction:column;
  justify-content: space-between;
}
#canvas {
  border: 1px dashed #ccc;
  background: #fff;
  width:100%;
  opacity: 0.8;
  display: inline-block;
}
* {
  touch-action: pan-y;
}
</style>
